{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "23fc7b95",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "  <td>\n",
    "    <a href=\"https://colab.research.google.com/github/nyandwi/machine_learning_complete/blob/main/9_nlp_with_tensorflow/1_intro_to_nlp_and_text_preprocessing.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "181af0b9",
   "metadata": {},
   "source": [
    "*This notebook was created by [Jean de Dieu Nyandwi](https://twitter.com/jeande_d) for the love of machine learning community. For any feedback, errors or suggestion, he can be reached on email (johnjw7084 at gmail dot com), [Twitter](https://twitter.com/jeande_d), or [LinkedIn](https://linkedin.com/in/nyandwi).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "304ad719",
   "metadata": {
    "id": "304ad719"
   },
   "source": [
    "<a name='0'></a>\n",
    "# Intro to NLP and Text Processing with TensorFlow"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6a095ea",
   "metadata": {
    "id": "b6a095ea"
   },
   "source": [
    "## Contents \n",
    "\n",
    "* [1. Intro to Natural Language Processing](#1)\n",
    "* [2. Text Processing with TensorFlow](#2)\n",
    "   * [2.1 Traditional Text Encoding](#2-1)\n",
    "   * [2.2 Text Encoding with Tokenizer](#2-2)\n",
    "   * [2.3 Converting Texts into Sequence of Tokens](#2-3)\n",
    "   * [2.4 Padding Texts Sequences](#2-4)\n",
    "\n",
    "\n",
    "* [3. Using TextVectorization](#3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "NpH129c1ipzK",
   "metadata": {
    "id": "NpH129c1ipzK"
   },
   "source": [
    "<a name='1'></a>\n",
    "## 1. Intro to Natural Language Processing"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "k5UFpc8Wlwou",
   "metadata": {
    "id": "k5UFpc8Wlwou"
   },
   "source": [
    "We are surrounded by intelligent machines that can not only see the world, but also can understand and talk with us. \n",
    "\n",
    "That is not exagerating. At regular basis, some of us interact with virtual assistants such as Siri, Amazon Alexa, and Google Assistant. And there are thousands of chatbots that we interact with on many software applications and websites. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "UFMFGCdwiw5k",
   "metadata": {
    "id": "UFMFGCdwiw5k"
   },
   "source": [
    "NLP or Natural Language Processing is an interdisciplinary field. It is a branch of computer science, machine learning, and [computational linguistic](https://en.wikipedia.org/wiki/Computational_linguistics) that is concerned with giving the computers the ability to understand texts and human languages. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dpBLd7d9nWeL",
   "metadata": {
    "id": "dpBLd7d9nWeL"
   },
   "source": [
    "### Common tasks involved in NLP\n",
    "\n",
    "Below are some of the common tasks that can be done with NLP. \n",
    "\n",
    "* Text classification\n",
    "* Sentiment analysis\n",
    "* Text generation\n",
    "* Machine translation\n",
    "* Speech recognition \n",
    "* Text to speech conversion\n",
    "* Optical character recognition"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "xX9u2oWqoyKD",
   "metadata": {
    "id": "xX9u2oWqoyKD"
   },
   "source": [
    "#### Example Applications of NLP\n",
    "\n",
    "* Spam detection \n",
    "* Question answering\n",
    "* Language to language translation (Machine translation)\n",
    "* Grammatical error correction (like Grammarly)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t9hwpP2OsAuB",
   "metadata": {
    "id": "t9hwpP2OsAuB"
   },
   "source": [
    "One of the classical NLP tool is [NLTK](https://www.nltk.org). Natural Language Toolkit or NLTK provides different functionalities for working with texts and it is commonly used. \n",
    "\n",
    "In this lab and later lab, we won't use NLTK. We will use Keras and TensorFlow texts functions. \n",
    "\n",
    "There is also a suite of TensorFlow libraries for text processing such as [TensorFlow Text](https://www.tensorflow.org/text/guide/tf_text_intro). "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "agnu0_0BtDI8",
   "metadata": {
    "id": "agnu0_0BtDI8"
   },
   "source": [
    "<a name='2'></a>\n",
    "## 2. Intro to Text Processing with TensorFlow"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3HxsMh_stRSo",
   "metadata": {
    "id": "3HxsMh_stRSo"
   },
   "source": [
    "<a name='2-1'></a>\n",
    "\n",
    "### 2.1 Text encodings"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "-Gqg3FZYtWr5",
   "metadata": {
    "id": "-Gqg3FZYtWr5"
   },
   "source": [
    "Most machine learning models (including deep learning ones) can not handle text data. They have to be converted into numerics. In essence, that's what text encoding means: it's converting the text into numerics representation. \n",
    "\n",
    "There are 4 main texts encoding techniques which are: \n",
    "* Character encoding\n",
    "* Words based encoding\n",
    "* One hot encoding\n",
    "* Word embeddings\n",
    "\n",
    "Let's talk about these techniques in details. \n",
    "\n",
    "#### Character Based Encoding\n",
    "\n",
    "In this type of encoding technique, each character in a word is represented by unique number. \n",
    "\n",
    "One of the traditional character encoding technique is ASCII(American Standard Code Information Interchange). With ASCII, we can nearly convert any character to numeric, and it's pretty standard, but one of the disadvantages is that the antigrams (words with same letters in different order) can have the same encodings, and that can hurt the machine learrning model. \n",
    "\n",
    "Example of antigrams include `United` and `Unitied`, `Silent` and `Listen`. \n",
    "\n",
    "Character encoding is not widely used and it's less efficient compared to other later techniques. \n",
    "\n",
    "The image below shows character encoding done on antigrams.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "qwc5yF2Q8eDP",
   "metadata": {
    "id": "qwc5yF2Q8eDP"
   },
   "source": [
    "![Character encoding.png]()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ChXVjzLF8sjh",
   "metadata": {
    "id": "ChXVjzLF8sjh"
   },
   "source": [
    "#### Words Based Encoding"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5EtCffkENeJB",
   "metadata": {
    "id": "5EtCffkENeJB"
   },
   "source": [
    "In word based encoding, instead of taking a single character in a word, we represent all the individual words with numbers. \n",
    "\n",
    "In most cases, words encoding works well than character encodings. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "nM6LVlnw8jAk",
   "metadata": {
    "id": "nM6LVlnw8jAk"
   },
   "source": [
    "![Word encoding.png]()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "-mTdZhrEPgPT",
   "metadata": {
    "id": "-mTdZhrEPgPT"
   },
   "source": [
    "#### One Hot Encoding"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "SFjNamLou4pe",
   "metadata": {
    "id": "SFjNamLou4pe"
   },
   "source": [
    "One hot encoding is another encoding technique that is most known for [encoding categorical features](https://jeande.medium.com/your-onestop-guide-on-handling-categorical-features-5988caaef78a). Although it's not an effective, it can also be used for texts encoding, and the idea is to convert each words in a sentence into one hot vector, where that word will be `1(hot)` and all other words be `0(cold)` in such particular vector. \n",
    "\n",
    "Take for instance the sentence `I love this course`. We can take words in such sentence [I, love, this, course] and then create a zero vector with length of 4, and then have 1 on the index that corresponds to the every word as it is shown below. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "rMlmzsFiyc0H",
   "metadata": {
    "id": "rMlmzsFiyc0H"
   },
   "source": [
    "![Blog Covers-2.png]()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "jGcbgsmjyho6",
   "metadata": {
    "id": "jGcbgsmjyho6"
   },
   "source": [
    "One hot encoding is not a better way to represent texts because most indices are zero and it becomes even harder when you have many words. It will take a lot of space in memory.\n",
    "\n",
    "By far, in all encoding techniques we saw (character encoding, word encoding, and one hoting words), words encoding is a good way to represent texts. But there is a more better way that is called word embeddings. \n",
    "\n",
    "Words embeddings are another way to represent texts where each word is converted into a feature vector, and vectors of the words that have the same semantic meaning will have the same direction in a high dimensional space. We will learn more about embeddings in the next notebook, but if you want you can play with them [here](http://projector.tensorflow.org)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "u2SDR8h32fE9",
   "metadata": {
    "id": "u2SDR8h32fE9"
   },
   "source": [
    "<a name='2-2'></a>\n",
    "\n",
    "### 2.2 Text Encoding with Keras Tokenizer"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9tDuayp80W1M",
   "metadata": {
    "id": "9tDuayp80W1M"
   },
   "source": [
    "Tokenizer is a Keras text preprocessing function that makes it easy to convert a raw text into tokens or sequence of integers.  \n",
    "\n",
    "\n",
    "We can use [Tokenizer](https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/text/Tokenizer) to encode texts at character or words level. \n",
    "\n",
    "We will most of the time prefer words encoding than character encoding to avoid the problems that can be caused by antigram words (the words that has the same characters in different order, ex: united & unitied, listen & silent, restful & fluster).\n",
    "\n",
    "Let's import TensorFlow and Tokenizer and we will start tokenizing texts right away. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "p0xa7WWe45-L",
   "metadata": {
    "id": "p0xa7WWe45-L"
   },
   "source": [
    "#### Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "alBwiPau5LC9",
   "metadata": {
    "id": "alBwiPau5LC9"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.keras.preprocessing.text import Tokenizer"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "v4-e7mAL5X5L",
   "metadata": {
    "id": "v4-e7mAL5X5L"
   },
   "source": [
    "Before we start converting texts into tokens, let's see all the possibilities available in `Tokenizer`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "vA2XOF3W5tpK",
   "metadata": {
    "id": "vA2XOF3W5tpK"
   },
   "source": [
    "Tokenizer arguments\n",
    "\n",
    "```\n",
    "■ num_words: the maximum number of words to keep in input text. It's always better to set a high number of you're not sure. If you set a number less than words that you have in texts, the rest will not tokenized.\n",
    "\n",
    "■ filters: By default, all punctuations and tabs will be removed. If you want to change that, you can provide the punctuations that you want to keep. \n",
    "\n",
    "■ lower: This is to be True or False. By default, it is True and that means all texts will be converted to lower case.\n",
    "\n",
    "split: separator for splitting words. A default separator is a space(\" \"). If in your texts words are splitted by something else, be sure to mention that there. \n",
    "\n",
    "■ char_level: If True, every character will be treated as token. It is False by default.\n",
    "\n",
    "■ oov_token: This denotes something that to be added to the word_index to replace words that are not available in input text. \n",
    "\n",
    "And the last thing to note is that tokens starts at 1.\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "-luSjkz-98vO",
   "metadata": {
    "id": "-luSjkz-98vO"
   },
   "source": [
    "#### Getting the Text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ukaI1bnr-pMm",
   "metadata": {
    "id": "ukaI1bnr-pMm"
   },
   "source": [
    "For simplicity, let's explore the all possibilities of Keras's Tokenizer using a simple sentences. Later, we will practice the skills on real world datasets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "CNUzPUWIDfGi",
   "metadata": {
    "id": "CNUzPUWIDfGi"
   },
   "outputs": [],
   "source": [
    "# A sample sentence\n",
    "\n",
    "sentences = ['TensorFlow is a Machine Learning framework',\n",
    "             'Keras is a well designed deep learning API',\n",
    "             'TensorFlow and Keras make a great machine learning ecosystem'\n",
    "              \n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "kLWx4ADIDFDX",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "kLWx4ADIDFDX",
    "outputId": "b00427d3-65cf-4c3e-8113-3e3523583ff8"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['TensorFlow is a Machine Learning framework',\n",
       " 'Keras is a well designed deep learning API',\n",
       " 'TensorFlow and Keras make a great machine learning ecosystem']"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sentences"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eP3igoipEMDW",
   "metadata": {
    "id": "eP3igoipEMDW"
   },
   "source": [
    "Let's instiate our Tokenizer. We will assume that the number of words are 1000. \n",
    "\n",
    "Note that by setting `char_level` to true, we will are converting each character as a token. This is not feasible as we have seen early. It becomes a problems for words that have same characters in different order(antigrams) because their tokens will be ultimately the same. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "vr496JvAEEIN",
   "metadata": {
    "id": "vr496JvAEEIN"
   },
   "outputs": [],
   "source": [
    "tokenizer = Tokenizer(num_words=1000, char_level=True)\n",
    "\n",
    "# Fitting tokenizer on sentences\n",
    "tokenizer.fit_on_texts(sentences)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "_n39kkPvGQV7",
   "metadata": {
    "id": "_n39kkPvGQV7"
   },
   "source": [
    "Let's get the character index, a dictionary that map each character to its token."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "R7ztDhDIGPuo",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "R7ztDhDIGPuo",
    "outputId": "f47fc01b-cb23-492c-da4e-7ca40c3d812e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{' ': 1, 'e': 2, 'a': 3, 'n': 4, 'r': 5, 's': 6, 'i': 7, 'l': 8, 'o': 9, 'm': 10, 'g': 11, 't': 12, 'w': 13, 'k': 14, 'd': 15, 'f': 16, 'c': 17, 'h': 18, 'p': 19, 'y': 20}\n"
     ]
    }
   ],
   "source": [
    "char_index = tokenizer.word_index\n",
    "print(char_index)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "uemMRwYrGwpb",
   "metadata": {
    "id": "uemMRwYrGwpb"
   },
   "source": [
    "In real world dataset, you would not want to do that. Let's see what happens when we tokenize words instead of characters. \n",
    "\n",
    "It's only just setting `char_level` to `False`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tpIE4S3PHCbY",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "tpIE4S3PHCbY",
    "outputId": "799f2d90-9ace-431e-f99f-7e6bfa5d582a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 1, 'learning': 2, 'tensorflow': 3, 'is': 4, 'machine': 5, 'keras': 6, 'framework': 7, 'well': 8, 'designed': 9, 'deep': 10, 'api': 11, 'and': 12, 'make': 13, 'great': 14, 'ecosystem': 15}\n"
     ]
    }
   ],
   "source": [
    "tokenizer = Tokenizer(num_words=1000)\n",
    "\n",
    "# Fitting tokenizer on sentences\n",
    "tokenizer.fit_on_texts(sentences)\n",
    "\n",
    "word_index = tokenizer.word_index\n",
    "print(word_index)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "NGmvr6I2GwwJ",
   "metadata": {
    "id": "NGmvr6I2GwwJ"
   },
   "source": [
    "As you can see, rather than having tokens of characters, we have tokens of words and that's more meaningful. By default, punctuations are removed. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ZAJYp5sAIstj",
   "metadata": {
    "id": "ZAJYp5sAIstj"
   },
   "source": [
    "Also, we can get how many times each word appears in a sentence/document."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "XOb-6DGTIIDp",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "XOb-6DGTIIDp",
    "outputId": "e3da1eed-ac57-473f-8acd-f874b6f29828"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "OrderedDict([('tensorflow', 2),\n",
       "             ('is', 2),\n",
       "             ('a', 3),\n",
       "             ('machine', 2),\n",
       "             ('learning', 3),\n",
       "             ('framework', 1),\n",
       "             ('keras', 2),\n",
       "             ('well', 1),\n",
       "             ('designed', 1),\n",
       "             ('deep', 1),\n",
       "             ('api', 1),\n",
       "             ('and', 1),\n",
       "             ('make', 1),\n",
       "             ('great', 1),\n",
       "             ('ecosystem', 1)])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "word_counts = tokenizer.word_counts\n",
    "word_counts"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "blU2f5-zJTtX",
   "metadata": {
    "id": "blU2f5-zJTtX"
   },
   "source": [
    "That's it for Tokenization. \n",
    "\n",
    "Tokens are not enough and they are not in any order. It's also best to follow the sequence of input sentences. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "TacIue8jKv7C",
   "metadata": {
    "id": "TacIue8jKv7C"
   },
   "source": [
    "<a name='2-3'></a>\n",
    "\n",
    "### 2.3 Converting the Texts into Sequence of Tokens\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "mvIpYEqCbCHL",
   "metadata": {
    "id": "mvIpYEqCbCHL"
   },
   "source": [
    "Instead of getting tokens and stops there, we can also take anoother step further: converting sentence into sequence of tokens. \n",
    "\n",
    "This is important because it preserve the sequence of the words in sentence. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "zRUl_EZUcIvC",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "zRUl_EZUcIvC",
    "outputId": "8fd6952f-8016-4338-f7dc-a4cfdd6982e5"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['TensorFlow is a Machine Learning framework',\n",
       " 'Keras is a well designed deep learning API',\n",
       " 'TensorFlow and Keras make a great machine learning ecosystem']"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sentences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "MnX5boRFbyXM",
   "metadata": {
    "id": "MnX5boRFbyXM"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.preprocessing.text import Tokenizer\n",
    "\n",
    "# Redefining our sentence\n",
    "\n",
    "sentences = ['TensorFlow is a Machine Learning framework',\n",
    "             'Keras is a well designed deep learning API',\n",
    "             'TensorFlow and Keras make a great machine learning ecosystem!',\n",
    "             'TensorFlow is built on top of Keras',\n",
    "             'TensorFlow revolves around tensors!'\n",
    "              \n",
    "]\n",
    "\n",
    "tokenizer = Tokenizer(num_words=1000)\n",
    "tokenizer.fit_on_texts(sentences)\n",
    "word_index = tokenizer.word_index\n",
    "\n",
    "# Converting text to sequences\n",
    "\n",
    "text_sequences = tokenizer.texts_to_sequences(sentences)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "J43ne2nedIZh",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "J43ne2nedIZh",
    "outputId": "1292668a-d628-4482-bbc2-49b2d6f77635"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Words with tokens: {'tensorflow': 1, 'is': 2, 'a': 3, 'learning': 4, 'keras': 5, 'machine': 6, 'framework': 7, 'well': 8, 'designed': 9, 'deep': 10, 'api': 11, 'and': 12, 'make': 13, 'great': 14, 'ecosystem': 15, 'built': 16, 'on': 17, 'top': 18, 'of': 19, 'revolves': 20, 'around': 21, 'tensors': 22}\n",
      "Sequence of tokens: [[1, 2, 3, 6, 4, 7], [5, 2, 3, 8, 9, 10, 4, 11], [1, 12, 5, 13, 3, 14, 6, 4, 15], [1, 2, 16, 17, 18, 19, 5], [1, 20, 21, 22]]\n"
     ]
    }
   ],
   "source": [
    "print(f'Words with tokens: {word_index}')\n",
    "print(f'Sequence of tokens: {text_sequences}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "s2z1ANwUdt2y",
   "metadata": {
    "id": "s2z1ANwUdt2y"
   },
   "source": [
    "From the above words-tokens dictionary and sequences' list, the first list in sequence is `[1, 2, 3, 6, 4, 7]`. It should represent the first sentence in our input sentences(`TensorFlow is a Machine Learning framework`). You can use the word index to verify that. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4832s6thIYV",
   "metadata": {
    "id": "e4832s6thIYV"
   },
   "source": [
    "In the case you expect to provide sentence that have words that tokenizer wasn't fitted at, it's best to create initiate a tokenizer with `oov_token` so that these new words are marked and the oov token will be used to replace these words that are out of vocabulary during text to sequence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "EHy4egiNh1dg",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "EHy4egiNh1dg",
    "outputId": "0065eaad-e86c-44b9-fbac-d7e6e0f4ca73"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Words with tokens: {'Word Out of Vocab': 1, 'tensorflow': 2, 'is': 3, 'a': 4, 'learning': 5, 'keras': 6, 'machine': 7, 'framework': 8, 'well': 9, 'designed': 10, 'deep': 11, 'api': 12, 'and': 13, 'make': 14, 'great': 15, 'ecosystem': 16, 'built': 17, 'on': 18, 'top': 19, 'of': 20, 'revolves': 21, 'around': 22, 'tensors': 23}\n",
      "Sequence of tokens: [[2, 3, 4, 7, 5, 8], [6, 3, 4, 9, 10, 11, 5, 12], [2, 13, 6, 14, 4, 15, 7, 5, 16], [2, 3, 17, 18, 19, 20, 6], [2, 21, 22, 23]]\n"
     ]
    }
   ],
   "source": [
    "tokenizer = Tokenizer(num_words=1000, oov_token='Word Out of Vocab')\n",
    "tokenizer.fit_on_texts(sentences)\n",
    "word_index = tokenizer.word_index\n",
    "\n",
    "# Converting text to sequences\n",
    "\n",
    "text_sequences = tokenizer.texts_to_sequences(sentences)\n",
    "\n",
    "print(f'Words with tokens: {word_index}')\n",
    "print(f'Sequence of tokens: {text_sequences}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2Bnw7dUui5Kv",
   "metadata": {
    "id": "2Bnw7dUui5Kv"
   },
   "source": [
    "The `oov_token` takes the first index in dictionary of words-tokens.\n",
    "\n",
    "So if we now pass new words to the tokenizer(without fitting on them like we did before), it will be replaced by 1 in the output sequence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "x7mHGlEjjOG_",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "x7mHGlEjjOG_",
    "outputId": "0b7cd6a6-e74a-4414-8c90-6446e54e43de"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sequence of tokens: [[1, 1, 2], [6, 3, 4, 1, 11, 5, 12]]\n"
     ]
    }
   ],
   "source": [
    "new_sentences = ['I like TensorFlow', # like is a new word\n",
    "                'Keras is a superb deep learning API' # superb is a new word\n",
    "                \n",
    "] \n",
    "\n",
    "sequences_on_newtexts = tokenizer.texts_to_sequences(new_sentences)\n",
    "print(f'Sequence of tokens: {sequences_on_newtexts}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "C-CkJZzQkmuZ",
   "metadata": {
    "id": "C-CkJZzQkmuZ"
   },
   "source": [
    "Looking on the above sequence, you can see that the `oov_token`(having index 1 in word dictionary) has replaced all new words(`I, like, superb`)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "206zgMG2lVrA",
   "metadata": {
    "id": "206zgMG2lVrA"
   },
   "source": [
    "To take things further again, let's look into one more thing that is required in nearly all datasets preprocessing: making sure that the inputs data are equal in size."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "zt7W6Gdflok5",
   "metadata": {
    "id": "zt7W6Gdflok5"
   },
   "source": [
    "<a name='2-4'></a>\n",
    "\n",
    "### 2.4 Padding the Sequences to Have the Same Length\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lUfBkgJimHpo",
   "metadata": {
    "id": "lUfBkgJimHpo"
   },
   "source": [
    "Nearly all machine learning models require the input samples to have the same length/size. Take an example: in computer vision with convolutional neural networks, we always have to resize all images to have the same size. \n",
    "\n",
    "This is not an optional step. Below are different options available when padding sequences in Keras.\n",
    "\n",
    "```\n",
    "tf.keras.preprocessing.sequence.pad_sequences(\n",
    "    sequences, maxlen=None, dtype=\"int32\", padding=\"pre\", truncating=\"pre\", value=0.0\n",
    ")\n",
    "```\n",
    "Notes on arguments:\n",
    "\n",
    "```\n",
    "• sequence: This is a list of sequences in integer forms (tokenized texts).\n",
    "\n",
    "• maxlen: Maximum length of all sequences. If not provided, sequences will be padded to the length of the longest sequence in provided sequences.\n",
    "\n",
    "• padding: 'pre' or `post`. Choose `pre` to padd before the sequence or `post` to padd after the sequence. By default, the sequence are pre-padded. \n",
    "\n",
    "• truncating: 'pre' or `post`. Remove the values from sequences larger than maxlen, either at the beginning or at the end of the sequences.\n",
    "\n",
    "• value: a float or a string that you want to use as a padding value. By default, the sequences are padded with 0.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "GivRq0OXpsMX",
   "metadata": {
    "id": "GivRq0OXpsMX"
   },
   "source": [
    "Let's practice it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "THGFuC2aptzs",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "THGFuC2aptzs",
    "outputId": "e198317b-f145-42fc-f53f-9338ad60ee7c"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WORD INDEX\n",
      "Words with tokens: {'Word Out of Vocab': 1, 'tensorflow': 2, 'is': 3, 'a': 4, 'learning': 5, 'keras': 6, 'machine': 7, 'framework': 8, 'well': 9, 'designed': 10, 'deep': 11, 'api': 12, 'and': 13, 'make': 14, 'great': 15, 'ecosystem': 16, 'built': 17, 'on': 18, 'top': 19, 'of': 20, 'revolves': 21, 'around': 22, 'tensors': 23}\n",
      "---------\n",
      "SEQUENCES\n",
      "Words with tokens: [[2, 3, 4, 7, 5, 8], [6, 3, 4, 9, 10, 11, 5, 12], [2, 13, 6, 14, 4, 15, 7, 5, 16], [2, 3, 17, 18, 19, 20, 6], [2, 21, 22, 23]]\n",
      "---------\n",
      "PADDED SEQUENCES\n",
      "Sequence of tokens: [[ 0  0  0  0  2  3  4  7  5  8]\n",
      " [ 0  0  6  3  4  9 10 11  5 12]\n",
      " [ 0  2 13  6 14  4 15  7  5 16]\n",
      " [ 0  0  0  2  3 17 18 19 20  6]\n",
      " [ 0  0  0  0  0  0  2 21 22 23]]\n"
     ]
    }
   ],
   "source": [
    "from tensorflow.keras.preprocessing.sequence import pad_sequences\n",
    "\n",
    "# Padding text_sequences \n",
    "\n",
    "padded_sequences = pad_sequences(text_sequences, maxlen=10)\n",
    "\n",
    "\n",
    "print('WORD INDEX')\n",
    "print(f'Words with tokens: {word_index}')\n",
    "print(\"---------\")\n",
    "\n",
    "\n",
    "print('SEQUENCES')\n",
    "print(f'Words with tokens: {text_sequences}')\n",
    "print(\"---------\")\n",
    "\n",
    "print('PADDED SEQUENCES')\n",
    "print(f'Sequence of tokens: {padded_sequences}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "qgLaHzlYrf3j",
   "metadata": {
    "id": "qgLaHzlYrf3j"
   },
   "source": [
    "As you can see, the sequences are pre-padded with 0. In case we want to padd after the sequences, we can set `padding` to `post`. Also we can set padding value to something else, say -1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7i5cMbLQrthF",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "7i5cMbLQrthF",
    "outputId": "fd2362eb-53a3-43a6-b4de-9e87ebc0629b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PADDED SEQUENCES\n",
      "Sequence of tokens: [[ 2  3  4  7  5  8 -1 -1 -1 -1]\n",
      " [ 6  3  4  9 10 11  5 12 -1 -1]\n",
      " [ 2 13  6 14  4 15  7  5 16 -1]\n",
      " [ 2  3 17 18 19 20  6 -1 -1 -1]\n",
      " [ 2 21 22 23 -1 -1 -1 -1 -1 -1]]\n"
     ]
    }
   ],
   "source": [
    "padded_sequences = pad_sequences(text_sequences, maxlen=10, padding='post', value=-1)\n",
    "\n",
    "print('PADDED SEQUENCES')\n",
    "print(f'Sequence of tokens: {padded_sequences}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0_YUF3-lsBRD",
   "metadata": {
    "id": "0_YUF3-lsBRD"
   },
   "source": [
    "That's it for tokenization, sequences and padding. If you have wondered why all of this is done, you are not alone. But this is a basic way of preparing texts before feeding them to a machine learning model. \n",
    "\n",
    "And it's basically same for all learning algorithms. We have to prepare data to be in the right format accepted by the learning algorithm. The preparation required for text dataset are different to images for example. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "R45E02hfskwZ",
   "metadata": {
    "id": "R45E02hfskwZ"
   },
   "source": [
    "<a name='3'></a>\n",
    "\n",
    "## 3. Using TextVectorization Layer to Preprocess Texts"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "BaIlzPVGh54c",
   "metadata": {
    "id": "BaIlzPVGh54c"
   },
   "source": [
    "TextVectorization layer is a Keras preprocessing that is used to transform strings into a list of tokens. \n",
    "\n",
    "This layer will do 3 main things: \n",
    "\n",
    "\n",
    "* Standardize text samples(removing punctuations and lowering the text case)\n",
    "* Splitting a sentence into individual words and converting them to tokens\n",
    "* And converting the tokens into numbers that can be fed to a model. \n",
    "\n",
    "In few words, TextVectorization remove the punctuations from texts and lower the case(standardization), tokenize the sentences, and vectorize the tokens. \n",
    "\n",
    "Here are notes about the layer's argument:\n",
    "\n",
    "```\n",
    "tf.keras.layers.experimental.preprocessing.TextVectorization(\n",
    "    max_tokens=None,\n",
    "    standardize=\"lower_and_strip_punctuation\",\n",
    "    split=\"whitespace\",\n",
    "    ngrams=None,\n",
    "    output_mode=\"int\",\n",
    "    output_sequence_length=None,\n",
    "    pad_to_max_tokens=False,\n",
    "    vocabulary=None\n",
    ")\n",
    "```\n",
    "\n",
    "```\n",
    "* max_tokens: Maximum number of vocabulary size. A vocabulary is a list of individual or unique words in a sentence. \n",
    "\n",
    "* standardize: This is denote the standardization specifics to be applied to input data. By default, it is `lower_and_strip_punctuation' meaning to lower the case and remove punctuations.\n",
    "\n",
    "* split: This denote what will be considered while splitting the input text. By default it is `whitespace`, but if your text is different, you can mention it here. \n",
    "\n",
    "* output mode: Specify the type of output of layer. By default it is 'int', meaning the layer output will be integer indices. \n",
    "\n",
    "* vocabulary: an array or (list, set, tuple) of strings or a path to a text file. \n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "URb6BozHouX9",
   "metadata": {
    "id": "URb6BozHouX9"
   },
   "source": [
    "Let's put that into practice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "QfkdnmQkrSYw",
   "metadata": {
    "id": "QfkdnmQkrSYw"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "from tensorflow.keras.layers.experimental.preprocessing import TextVectorization"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "kFAAbtEZr3Yi",
   "metadata": {
    "id": "kFAAbtEZr3Yi"
   },
   "source": [
    "In TensorFlow 2.6 and above, this layer will not be in experimentals. It will be in [Preprocessing layers](https://keras.io/api/layers/preprocessing_layers/). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "x76D5avVlivO",
   "metadata": {
    "id": "x76D5avVlivO"
   },
   "outputs": [],
   "source": [
    "# Sample sentences\n",
    "\n",
    "sentences = [\n",
    "             'TensorFlow is a deep learning library!',\n",
    "             'Is TensorFlow powered by Keras API?'\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7eYMFefqscFA",
   "metadata": {
    "id": "7eYMFefqscFA"
   },
   "outputs": [],
   "source": [
    "max_features = 1000\n",
    "\n",
    "text_vect_layer = tf.keras.layers.TextVectorization(\n",
    "    max_tokens=max_features,\n",
    "    output_mode='int',\n",
    "    output_sequence_length=10\n",
    "\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aaOetzBexcPA",
   "metadata": {
    "id": "aaOetzBexcPA"
   },
   "source": [
    "We can use adapt() method to fit the sentences to a layer. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "GdYJMqYGuf4L",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "GdYJMqYGuf4L",
    "outputId": "087bfd03-45bb-4c5f-866e-2d8847fa85bb"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:6 out of the last 7 calls to <function PreprocessingLayer.make_adapt_function.<locals>.adapt_step at 0x7fa4e05ca9e0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.\n"
     ]
    }
   ],
   "source": [
    "text_vect_layer.adapt(sentences)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "UXT4hQTQxiZP",
   "metadata": {
    "id": "UXT4hQTQxiZP"
   },
   "source": [
    "Let's pass a sample sentence to a layer to see what kind of the output is."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "WyQWnWL-xDV0",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "WyQWnWL-xDV0",
    "outputId": "6a2a9f4d-688d-4e98-d6a4-1ec53ae37070"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Orginal sentence: \n",
      " Tensorflow is a machine learning framework!\n",
      "Vectorized sentence: \n",
      " [[ 2  3 10  1  6  1  0  0  0  0]]\n"
     ]
    }
   ],
   "source": [
    "sample_sentence = 'Tensorflow is a machine learning framework!'\n",
    "\n",
    "vectorized_sentence = text_vect_layer([sample_sentence])\n",
    "\n",
    "print(f'Orginal sentence: \\n {sample_sentence}')\n",
    "print(f'Vectorized sentence: \\n {vectorized_sentence}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "No7WUUUhylIG",
   "metadata": {
    "id": "No7WUUUhylIG"
   },
   "source": [
    "If you can notice, both `machine` and `framework` were not part of the sentences we adapted to the layer before and they are represented by `1` in the vectorized output. This is to mean that indice 1 is reserved for words that are out of vocabulary(`oov_token`).\n",
    "\n",
    "You can also see that the output is padded with 0 as the output sequence size is 10. \n",
    "\n",
    "The layer basically do all required preprocessing at once. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aG5ApcHjvrfB",
   "metadata": {
    "id": "aG5ApcHjvrfB"
   },
   "source": [
    "One of the great advantage of having this layer is that it can be used inside a model. So you can have a model that accept texts at the input, transform it, and model it..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9UPcWTSIzRoh",
   "metadata": {
    "id": "9UPcWTSIzRoh"
   },
   "source": [
    "We will use this layer in later practice. If you want to learn more, check out the [documentation](https://www.tensorflow.org/api_docs/python/tf/keras/layers/TextVectorization). It's pretty detailed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "GL3lZSlTretR",
   "metadata": {
    "id": "GL3lZSlTretR"
   },
   "source": [
    "This is the end of the lab. NLP is a machine learning field that deals with texts. \n",
    "\n",
    "Both NLP and Computer Vision are two of the most exciting fields in AI and machine learning and being able to know them can help you build cross applications. For example, given an image of a kid playing basketball, you can use computer vision techniques to recognize image, and generate a caption with NLP techniques. That's awesome, right!? \n",
    "\n",
    "So, in the lab we also learned how to represent texts as numbers because the input data to most machine learning models must be vectors or array of numbers. We saw how to tokenize words, convert tokens into sequences, and padd the sequences. Also we saw how to convert texts into vectors or numbers with TextVectorization layer. \n",
    "\n",
    "In the next lab, we will learn about another useful texts representation techniques called word embeddings. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "FoXsg_65uqk4",
   "metadata": {
    "id": "FoXsg_65uqk4"
   },
   "source": [
    "## [BACK TO TOP](#0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "O6vVv5L_acn8",
   "metadata": {
    "id": "O6vVv5L_acn8"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "9.1 Intro to Natural Language Processing with TensorFlow.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3.7.10 64-bit ('tensor': conda)",
   "language": "python",
   "name": "python3710jvsc74a57bd034ac5db714c5906ee087fcf6e2d00ee4febf096586592b6ba3662ed3b7e7a5f6"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
